package com.sky.interceptor;

import com.sky.constant.DishAOPConstant;
import com.sky.constant.PreConstant;
import com.sky.entity.Dish;
import com.sky.service.IDishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

//@Component
public class DishInterceptor implements HandlerInterceptor {
    //拦截请求，用于拦截对菜品修改的时候，
    //进行解放缓存
//    @Autowired
    private RedisTemplate redisTemplate;
//    @Autowired
    private IDishService iDishService;

//换成Spring Cache 缓存注解
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //先从请求行中找有没有  id，或者ids
        String id = request.getParameter(DishAOPConstant.ID);
        if (id!=null) {
           String categoryId = iDishService.getById(id).getCategoryId()+"";
            redisTemplate.delete(PreConstant.PRE_DISH+ categoryId);
            return true;
        }
        //如果没有再从请求头中找categoryId;
        String  categoryId = request.getHeader(DishAOPConstant.CATEGORYID);
        if (categoryId!=null){
            redisTemplate.delete(PreConstant.PRE_DISH+ categoryId);
            return true;
        }
        //如果还是没有则找ids
        //前端传过来的是ids=1，2，4 所以在mybatis-plus里面只能用getParameter
        String idstr = request.getParameter(DishAOPConstant.IDS);
        if (idstr!=null) {
            String[] ids = idstr.split(",");
            List<Dish> dishes = iDishService.listByIds(Arrays.asList(ids));
            //用list,得到的可能都是同一菜系的菜品
            Set<Long> collect = dishes.stream().map(Dish::getCategoryId).collect(Collectors.toSet());
            collect.forEach(cateId-> redisTemplate.delete(PreConstant.PRE_DISH + cateId));

        }
        return true;
    }
}
